package com.klcw.distributedCommunication.serialization;

import java.io.*;

/**
 * @ClassName SerializeDemo
 * @Description 序列化
 * @Author dukang
 * @Date 2019/1/22 10:48
 * @Version 1.0
 **/
public class SerializeDemo {

    public static void main(String[] args) {
        SerializePerson();
        Persons.height = 5;
        Persons persons = DeSerializePerson();
        System.out.println(persons);
    }

    // 序列化操作
    private static void SerializePerson(){
        try {
            ObjectOutputStream stream = new ObjectOutputStream(new FileOutputStream(new File("persons")));
            Persons persons = new Persons();
            persons.setAge("16");
            persons.setName("dukang");
            stream.writeObject(persons);
            System.out.println("序列化成功");
            // 关闭流对象
            stream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 反序列化
    public static Persons DeSerializePerson(){
        try {
            // 文件读入流对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("persons")));
            // 读取Object流对象
            Persons person = (Persons) ois.readObject();
            return person;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
